package com.herohead.backup;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import com.herohead.redis.RedisKeys;
import com.herohead.redis.RedisVars;

public class Groups {

	static BufferedReader br;
	static String line = "";
	static Jedis jd;
	static Transaction tx;


	public static  void cleanupKeys(Jedis jd,String key) {
		Set<String> licAppList  = jd.smembers(key);

		for (String verKey : licAppList ) {
			jd.del(verKey);
		}

		jd.del(key);

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String inputFile = args[0];

		try {
			br = new BufferedReader(new FileReader(inputFile));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		//GetRedisServer grs = new GetRedisServer();
		//String redisHost = getredis.getRedisHost();

		RedisVars.redisHost = "localhost";

		jd = new Jedis(RedisVars.redisHost);

		Jedis jdpl = new Jedis(RedisVars.redisHost);
		tx = jdpl.multi();

		String val;
		String clientVal = null;

		cleanupKeys(jd,RedisKeys.sProdNWEUGroupKeys);
		jd.del(RedisKeys.zProdNWEUGroupCount);

		//System.exit(0);

		try {
			line = br.readLine();
			while (line != null) {

				if (line.contains("Current query set")) {line = br.readLine(); continue;}
				line  = line.trim().replaceAll("\\s+", " ");
				line = line.replaceAll(";", "");

				//System.out.println(line);

				System.out.println(line);

				String[] s = line.split(":");

				if (s[0].contains("name")) {
					val = s[1].trim();
					clientVal = val;
				}
				if (s[0].contains("group")) {
					val = s[1].replaceAll(" ", "");
					//val = val.replace(";", "");
					String[] vals = val.split(",");
					for (String s1 : vals) {
						tx.sadd(RedisKeys.sProdNWEUGroupList + s1, clientVal);
						System.out.println(RedisKeys.sProdNWEUGroupList + s1 + "," +  clientVal);
						tx.sadd(RedisKeys.sProdNWEUGroupKeys,RedisKeys.sProdNWEUGroupList + s1);
						tx.zincrby(RedisKeys.zProdNWEUGroupCount, 1, s1);
					}
				}
				line = br.readLine();
			}

			tx.exec();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
